package edu.sctu.zhoumengxue.day201506.day20150619.getandpostURL;


import com.sun.javafx.collections.MappingChange;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
/**
 * Created by user12 on 2015/6/19.
 */
public class URLGetAndPost {

    public void getURL(String path){

        int count ;
        byte[] bytes = new byte[1024];

        try {
            URL url = new URL(path);
            try {
                URLConnection connection = url.openConnection();
                connection.setDoInput(true);
                connection.connect();

                InputStream in = connection.getInputStream();

                while((count=in.read(bytes))!=-1){
                    System.out.println(new String(bytes,0,count,"utf-8"));
                }
                in.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public void postURL(String path,String param){
        int count;
        byte[] bytes = new byte[1024];

        try {
            URL url = new URL(path);
            try {
                HttpURLConnection http = (HttpURLConnection) url.openConnection();
                http.setRequestMethod("POST");
                http.setDoInput(true);
                http.setDoOutput(true);
                http.connect();

                OutputStream out = http.getOutputStream();
                out.write(param.getBytes());
                out.close();

                InputStream in = http.getInputStream();
                while((count=in.read(bytes))!=-1){
                    System.out.println(new String(bytes,0,count,"utf-8"));
                }
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public String iteratorURL(HashMap<String,String> map){

        String param="";
        Iterator iterator = map.entrySet().iterator();

        while (iterator.hasNext()){

            String string = (String) iterator.next();
            param = param+string+"="+map.get(string)+"&";

        }
        return param;
    }


}
